<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑打手信息' : '添加新打手'"
    width="800px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    class="worker-form-dialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="worker-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="打手昵称" prop="nickname">
              <el-input
                v-model="formData.nickname"
                placeholder="请输入打手昵称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input
                v-model="formData.realName"
                placeholder="请输入真实姓名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="formData.phone"
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="formData.gender" placeholder="请选择性别">
                <el-option label="男" value="male" />
                <el-option label="女" value="female" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model="formData.age"
                :min="16"
                :max="60"
                placeholder="年龄"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="打手等级" prop="level">
              <el-select v-model="formData.level" placeholder="请选择等级">
                <el-option label="实习生" value="trainee" />
                <el-option label="初级" value="junior" />
                <el-option label="高级" value="senior" />
                <el-option label="专家" value="expert" />
                <el-option label="大师" value="master" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="初始状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态">
                <el-option label="空闲" :value="WorkerStatus.IDLE" />
                <el-option label="休息" :value="WorkerStatus.REST" />
                <el-option label="离线" :value="WorkerStatus.OFFLINE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 技能信息 -->
      <div class="form-section">
        <h3 class="section-title">技能标签</h3>
        <el-form-item label="游戏技能" prop="skills">
          <div class="skills-container">
            <el-tag
              v-for="(skill, index) in formData.skills"
              :key="index"
              closable
              @close="removeSkill(index)"
              class="skill-tag"
            >
              {{ skill }}
            </el-tag>
            <el-input
              v-if="skillInputVisible"
              ref="skillInputRef"
              v-model="skillInputValue"
              size="small"
              style="width: 120px"
              @keyup.enter="handleSkillInputConfirm"
              @blur="handleSkillInputConfirm"
            />
            <el-button
              v-else
              size="small"
              type="primary"
              :icon="Plus"
              @click="showSkillInput"
            >
              添加技能
            </el-button>
          </div>
          <div class="skill-suggestions">
            <span class="suggestion-label">常用技能：</span>
            <el-tag
              v-for="skill in commonSkills"
              :key="skill"
              size="small"
              effect="plain"
              @click="addCommonSkill(skill)"
              class="suggestion-tag"
            >
              {{ skill }}
            </el-tag>
          </div>
        </el-form-item>
      </div>

      <!-- 财务设置 -->
      <div class="form-section">
        <h3 class="section-title">财务设置</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分成比例" prop="commissionRate">
              <el-input-number
                v-model="formData.commissionRate"
                :min="0"
                :max="100"
                :precision="2"
                placeholder="分成比例"
                controls-position="right"
                style="width: 100%"
              />
              <span class="input-suffix">%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户状态" prop="accountStatus">
              <el-select v-model="formData.accountStatus" placeholder="请选择账户状态">
                <el-option label="活跃" value="active" />
                <el-option label="非活跃" value="inactive" />
                <el-option label="暂停" value="suspended" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 备注信息 -->
      <div class="form-section">
        <el-form-item label="备注信息">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { WorkerStatus } from '@renderer/store/modules/worker'
import type { Worker } from '@renderer/store/modules/worker'
import { workerApi } from '@renderer/api/worker'

// Props
interface Props {
  modelValue: boolean
  workerData?: Worker | null
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', worker: Worker): void
}

const props = withDefaults(defineProps<Props>(), {
  workerData: null
})

const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref()
const skillInputRef = ref()
const loading = ref(false)
const skillInputVisible = ref(false)
const skillInputValue = ref('')

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 是否编辑模式
const isEdit = computed(() => !!props.workerData)

// 表单数据
const formData = reactive({
  nickname: '',
  realName: '',
  phone: '',
  gender: '',
  age: undefined as number | undefined,
  level: '',
  status: WorkerStatus.IDLE,
  skills: [] as string[],
  commissionRate: undefined as number | undefined,
  accountStatus: 'active',
  remark: ''
})

// 常用技能
const commonSkills = [
  '王者荣耀', '英雄联盟', '和平精英', 'PUBG', 'CF穿越火线',
  '原神', '明日方舟', '崩坏三', 'LOL手游', 'APEX',
  '竞技模式', '娱乐陪玩', '技术指导', '聊天陪伴', '新手教学'
]

// 表单验证规则
const formRules = {
  nickname: [
    { required: true, message: '请输入打手昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 16, max: 60, message: '年龄必须在16-60岁之间', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择打手等级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择初始状态', trigger: 'change' }
  ],
  commissionRate: [
    { required: true, message: '请输入分成比例', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '分成比例必须在0-100%之间', trigger: 'blur' }
  ],
  accountStatus: [
    { required: true, message: '请选择账户状态', trigger: 'change' }
  ]
}

// 监听props变化，初始化表单数据
watch(() => props.workerData, (newData) => {
  if (newData) {
    // 编辑模式，填充现有数据
    Object.assign(formData, {
      nickname: newData.nickname || '',
      realName: newData.realName || '',
      phone: newData.phone || '',
      gender: newData.gender || '',
      age: newData.age,
      level: newData.level || '',
      status: newData.status || WorkerStatus.IDLE,
      skills: newData.skills || [],
      commissionRate: newData.commissionRate ? newData.commissionRate * 100 : undefined, // 从小数转换为百分比
      accountStatus: newData.accountStatus || 'active',
      remark: newData.notes || ''
    })
  } else {
    // 新增模式，重置表单
    resetForm()
  }
}, { immediate: true })

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    nickname: '',
    realName: '',
    phone: '',
    gender: '',
    age: undefined,
    level: '',
    status: WorkerStatus.IDLE,
    skills: [],
    commissionRate: undefined,
    accountStatus: 'active',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 技能相关方法
const removeSkill = (index: number) => {
  formData.skills.splice(index, 1)
}

const showSkillInput = () => {
  skillInputVisible.value = true
  nextTick(() => {
    skillInputRef.value?.focus()
  })
}

const handleSkillInputConfirm = () => {
  const inputValue = skillInputValue.value.trim()
  if (inputValue && !formData.skills.includes(inputValue)) {
    formData.skills.push(inputValue)
  }
  skillInputVisible.value = false
  skillInputValue.value = ''
}

const addCommonSkill = (skill: string) => {
  if (!formData.skills.includes(skill)) {
    formData.skills.push(skill)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()
    
    loading.value = true
    
    // 构建提交数据
    const submitData: any = {
      nickname: formData.nickname,
      realName: formData.realName,
      phone: formData.phone,
      gender: formData.gender,
      age: formData.age,
      level: formData.level,
      status: formData.status,
      skillTags: JSON.stringify(formData.skills),
      commissionRate: formData.commissionRate ? formData.commissionRate / 100 : 0, // 转换为小数
      accountStatus: formData.accountStatus,
      joinDate: new Date().toISOString().split('T')[0], // 设置入职日期为今天
      notes: formData.remark || ''
    }

    if (isEdit.value && props.workerData) {
      // 编辑模式 - 调用更新API
      const response = await workerApi.updateWorker(props.workerData.id, submitData)
      ElMessage.success('打手信息更新成功')
    } else {
      // 新增模式 - 调用创建API
      const response = await workerApi.createWorker(submitData)
      ElMessage.success('打手添加成功')
    }
    
    // 发送成功事件
    emit('success', submitData)
    handleClose()
    
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error !== false) { // 排除表单验证失败的情况
      ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
    }
  } finally {
    loading.value = false
  }
}

// 检查表单是否有未保存的数据
const hasUnsavedChanges = () => {
  return formData.nickname.trim() !== '' || 
         formData.realName.trim() !== '' || 
         formData.phone.trim() !== '' || 
         formData.skills.length > 0
}

// 关闭对话框
const handleClose = () => {
  if (loading.value) {
    ElMessage.warning('操作进行中，请稍候...')
    return
  }
  
  // 如果有未保存的数据，提示用户确认
  if (hasUnsavedChanges()) {
    ElMessageBox.confirm(
      '确定要关闭吗？未保存的数据将丢失。',
      '确认关闭',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      dialogVisible.value = false
      resetForm()
    }).catch(() => {
      // 用户取消关闭
    })
  } else {
    // 没有未保存数据，直接关闭
    dialogVisible.value = false
    resetForm()
  }
}
</script>

<style scoped>
.worker-form-dialog {
  --el-dialog-bg-color: rgba(40, 44, 52, 0.95);
  --el-dialog-title-font-size: 18px;
  --el-text-color-primary: rgba(255, 255, 255, 0.9);
  --el-text-color-regular: rgba(255, 255, 255, 0.8);
  --el-border-color: rgba(255, 255, 255, 0.2);
  --el-bg-color: rgba(255, 255, 255, 0.1);
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 20px;
  padding-bottom: 8px;
  border-bottom: 2px solid rgba(102, 126, 234, 0.3);
  position: relative;
}

.section-title::before {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 40px;
  height: 2px;
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.skills-container .skill-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  background: rgba(102, 126, 234, 0.2);
  border: 1px solid rgba(102, 126, 234, 0.3);
  color: #667eea;
}

.skill-suggestions {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.suggestion-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-right: 8px;
}

.suggestion-tag {
  margin-right: 6px;
  margin-bottom: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.suggestion-tag:hover {
  background: rgba(102, 126, 234, 0.1);
  border-color: rgba(102, 126, 234, 0.3);
  color: #667eea;
}

.input-suffix {
  margin-left: 8px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* Element Plus 组件样式覆盖 */
.worker-form-dialog :deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.8) !important;
  font-weight: 600;
}

.worker-form-dialog :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  border-radius: 8px !important;
  box-shadow: none !important;
}

.worker-form-dialog :deep(.el-input__inner) {
  background-color: transparent !important;
  color: rgba(255, 255, 255, 0.9) !important;
  border: none !important;
}

.worker-form-dialog :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5) !important;
}

.worker-form-dialog :deep(.el-textarea__inner) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  border-radius: 8px !important;
}

.worker-form-dialog :deep(.el-textarea__inner::placeholder) {
  color: rgba(255, 255, 255, 0.5) !important;
}

.worker-form-dialog :deep(.el-select .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.worker-form-dialog :deep(.el-select .el-input__inner) {
  color: rgba(255, 255, 255, 0.9) !important;
}

.worker-form-dialog :deep(.el-input-number .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.worker-form-dialog :deep(.el-input-number .el-input__inner) {
  color: rgba(255, 255, 255, 0.9) !important;
}

.worker-form-dialog :deep(.el-input-number__increase),
.worker-form-dialog :deep(.el-input-number__decrease) {
  background: rgba(255, 255, 255, 0.1) !important;
  border-left: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.6) !important;
}

.worker-form-dialog :deep(.el-input-number__increase:hover),
.worker-form-dialog :deep(.el-input-number__decrease:hover) {
  background: rgba(102, 126, 234, 0.2) !important;
  color: #667eea !important;
}

.worker-form-dialog :deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea, #764ba2) !important;
  border: none !important;
  color: white !important;
}

.worker-form-dialog :deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a67d8, #6b46c1) !important;
}

.worker-form-dialog :deep(.el-button--default) {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.8) !important;
}

.worker-form-dialog :deep(.el-button--default:hover) {
  background: rgba(255, 255, 255, 0.15) !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

.worker-form-dialog :deep(.el-tag) {
  background: rgba(102, 126, 234, 0.2) !important;
  border: 1px solid rgba(102, 126, 234, 0.3) !important;
  color: #667eea !important;
}

.worker-form-dialog :deep(.el-tag .el-tag__close) {
  color: #667eea !important;
}

.worker-form-dialog :deep(.el-tag .el-tag__close:hover) {
  background-color: rgba(102, 126, 234, 0.3) !important;
}
</style>